package com.dudu.service.impl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mortbay.log.Log;

import com.dudu.enumeration.H5CodeDefinition;
import com.dudu.service.IOperationPlatformCustAccountService;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.HttpRequest;

/**
 * 计费账户服务类
 * 
 * @author zx
 * 
 */
public class OperationPlatformCustAccountServiceImpl implements IOperationPlatformCustAccountService {
    private static final Logger log = Logger.getLogger(OperationPlatformCustAccountServiceImpl.class.getSimpleName());
    // private String url ="http://test.cloud.yonyoutelecom.cn";
    private static String url = DictionaryUtils.getValueByTypeAndKey("platform", "url");

    /**
     * 从运营平台获取计费账户相关信息 6.55 查询应用企业计费账号信息（计费账号和应用key）接口
     * 
     * @param orgCode
     *            第三方组织编码
     * @param app_key
     *            应用账号
     * @return
     */
    public String getAppCustInfo(String orgCode, String app_key) {
	log.info("OperationPlatformCustAccountServiceImpl.getAppCustInfo 查询应用企业计费账号信息（计费账号和应用key）接口");
	JSONObject jsonParam = new JSONObject();
	jsonParam.put("periphery_account", orgCode);
	jsonParam.put("app_key", app_key);
	String myurl = url + "/CombinationServer/getAppCustInfo";
	String data = HttpRequest.postData(myurl, jsonParam.toString());
	log.info("OperationPlatformCustAccountServiceImpl.getAppCustInfo url:" + myurl + "---request:" + jsonParam.toString());
	log.info("OperationPlatformCustAccountServiceImpl.getAppCustInfo response:" + data);
	return data;
    }

    /**
     * 8.32 可用余额资源综合接口
     * 
     * @param cust_account
     * @param app_key
     * @param product_key
     * @return
     */
    public JSONObject queryResourcesAndAccountInfo(String cust_account, String app_key, String product_key) {
	log.info("OperationPlatformCustAccountServiceImpl.queryResourcesAndAccountInfo 可用余额资源综合接口");
	JSONObject object = new JSONObject();
	try {
	    // 拼写相应传递参数
	    JSONObject jsonParam = new JSONObject();
	    if (StringUtils.isNotBlank(app_key)) {
		jsonParam.put("app_key", app_key);//
	    }
	    if (StringUtils.isNotBlank(product_key)) {
		jsonParam.put("product_key", product_key);
	    }
	    jsonParam.put("cust_account", cust_account);// 账号
	    // 调用运营平台
	    String Myurl = url + "/CombinationServer/queryResourceAndAccount";
	    String data = HttpRequest.postData(Myurl, jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.queryResourcesAndAccountInfo url:" + Myurl + "---request:" + jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.queryResourcesAndAccountInfo response:" + data);
	    object = JSONObject.fromObject(data);
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error("OperationPlatformCustAccountServiceImpl.queryResourcesAndAccountInfo 可用余额资源综合接口" + e);
	    object.put("result", "-1");
	    object.put("describe", "错误:" + e);
	}
	return object;
    }

    /**
     * 查询充值记录接口6.22 [未改upd]查询充值记录接口
     * 
     * @param cust_account
     *            账号
     * @param periphery_code
     *            外围系统编码
     * @param pay_result
     *            充值结果(00：成功，01：失败，02：处理中，03：取消,-1：全部)
     * @param pay_comefrom
     *            支付来源(pc:电脑web端，mbl:手机端，all:全部)
     * @param pay_style
     *            支付方式(ali:支付宝，cdp:充值卡，chn:畅捷支付，ptp:后台充值，all：全部)
     * @param start_time
     *            充值开始时间(yyyy-MM-dd HH:mm:ss)
     * @param end_time
     *            充值结束时间
     * @param page_no
     *            页码
     * @param page_size
     *            每页显示数据数量
     * @return
     */
    public JSONObject getChargeItems(String cust_account, String periphery_code, String pay_result, String pay_comefrom, String pay_style, String start_time, String end_time,
	    String page_no, String page_size) {
	log.info("OperationPlatformCustAccountServiceImpl.getChargeItems 查询充值记录接口");
	JSONObject object = new JSONObject();
	try {
	    // 拼写相应传递参数
	    JSONObject jsonParam = new JSONObject();
	    jsonParam.put("periphery_code", periphery_code);// 外围系统编码
	    jsonParam.put("cust_account", cust_account);// 账号
	    jsonParam.put("pay_result", pay_result);
	    jsonParam.put("pay_comefrom", pay_comefrom);
	    jsonParam.put("pay_style", pay_style);
	    jsonParam.put("start_time", start_time);
	    jsonParam.put("end_time", end_time);
	    jsonParam.put("page_no", page_no);
	    jsonParam.put("page_size", page_size);
	    // 调用运营平台
	    String Myurl = url + "/pubbase/api/charge/getChargeItems.do";
	    String data = HttpRequest.postData(Myurl, jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.getChargeItems url:" + Myurl + "---request:" + jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.getChargeItems response:" + data);
	    object = JSONObject.fromObject(data);
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error("OperationPlatformCustAccountServiceImpl.getChargeItems 查询充值记录接口" + e);
	    object.put("result", "-1");
	    object.put("describe", "错误:" + e);
	}
	return object;
    }

    /**
     * 6.16 注册用户限额查询接口
     * 
     * @param periphery_code
     *            外围系统编码
     * @param cust_account
     *            计费账号
     * @param userId
     *            外围系统用户账号
     * @return
     */
    public JSONObject queryOauthRelationUser(String periphery_code, String cust_account, String userId) {
	log.info("OperationPlatformCustAccountServiceImpl.queryOauthRelationUser 注册用户限额查询接口");
	JSONObject object = new JSONObject();
	try {
	    // 拼写相应传递参数
	    JSONObject jsonParam = new JSONObject();
	    jsonParam.put("periphery_code", periphery_code);// 外围系统编码
	    jsonParam.put("periphery_account", cust_account);// 账号
	    jsonParam.put("periphery_user_account", userId);
	    // 调用运营平台
	    String Myurl = url + "/CombinationServer/queryOauthRelationUser";
	    String data = HttpRequest.postData(Myurl, jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.queryOauthRelationUser url:" + Myurl + "---request:" + jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.queryOauthRelationUser response:" + data);
	    object = JSONObject.fromObject(data);
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error("OperationPlatformCustAccountServiceImpl.queryOauthRelationUser 注册用户限额查询接口" + e);
	    object.put("result", "-1");
	    object.put("describe", "错误:" + e);
	}
	return object;
    }

    /**
     * 8.18 调用接口请求码接口
     * 
     * @param periphery_code
     * @param api_code
     *            预请求接口编码(cardpay:充值卡充值接口;mbilepay:在线充值接口)
     * @return
     */
    public JSONObject getAskCode(String periphery_code, String api_code) {
	log.info("OperationPlatformCustAccountServiceImpl.getAskCode 调用接口请求码接口");
	JSONObject object = new JSONObject();
	try {
	    // 拼写相应传递参数
	    JSONObject jsonParam = new JSONObject();
	    jsonParam.put("periphery_code", periphery_code);// 外围系统编码
	    jsonParam.put("api_code", api_code);// 账号
	    // 调用运营平台
	    String Myurl = url + "/pubbase/api/askCode/getAskCode.do";
	    String data = HttpRequest.postData(Myurl, jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.getAskCode url:" + Myurl + "---request:" + jsonParam.toString());
	    log.info("OperationPlatformCustAccountServiceImpl.getAskCode response:" + data);
	    object = JSONObject.fromObject(data);
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error("OperationPlatformCustAccountServiceImpl.getAskCode 调用接口请求码接口" + e);
	    object.put("result", "-1");
	    object.put("describe", "错误:" + e);
	}
	return object;
    }

    /**
     * 从运营平台获取计费账户相关信息
     * 
     * @param orgCode
     *            第三方组织编码
     * @param app_key
     *            应用账号
     * @return
     */
    public String getCustInfo(String orgCode, String app_key) {
	String custAccount = null;
	try {
	    String custAccountObj = getAppCustInfo(orgCode, app_key);
	    if (StringUtils.isNotBlank(custAccountObj)) {
		JSONObject custAccountJson = JSONObject.fromObject(custAccountObj);
		if (!JSONUtils.isNull(custAccountJson)) {
		    String flag = custAccountJson.getString("flag");
		    if ("0000".equalsIgnoreCase(flag)) {
			custAccount = custAccountJson.getJSONArray("data").getJSONObject(0).getString("cust_account");
		    }
		}
	    }
	} catch (Exception ex) {
	    Log.info(ex.getMessage());
	}

	return custAccount;
    }

    /**
     * 根据custaccount和能力类型获取账户余额
     * 
     * @param custAccount
     *            计费账户
     * @param abilityType
     *            可以传递多个能力类型，用","分割
     * @return 能力类型的值为1，表示有余额，0代表没有余额
     */
    public JSONObject getAccountBalancesByAbilityType(String custAccount, String abilityType) {
	String[] ability_type = abilityType.split(",");
	JSONObject result = queryResourcesAndAccountInfo(custAccount, null, null);
	JSONObject resultData = new JSONObject();
	if (H5CodeDefinition.SUCCESS.getCode().equals(result.getString("flag"))) {
	    resultData.put("result", H5CodeDefinition.SUCCESS.getCode());
	    result = result.getJSONObject("data");
	    double account_data = result.getDouble("account_data");
	    if (account_data > 0) {// 存在余额
		for (int i = 0, l = ability_type.length; i < l; i++) {
		    resultData.put(ability_type[i], "1");
		}
	    } else {
		JSONArray resources = result.getJSONArray("resource_data");
		boolean emptyResources = false;
		if (resources == null || resources.isEmpty()) {// 资源为空
		    emptyResources = true;
		}
		for (int i = 0, l = ability_type.length; i < l; i++) {
		    if (emptyResources) {
			resultData.put(ability_type[i], "0");
		    } else {
			boolean match = false;
			for (int j = 0; j < resources.size(); j++) {
			    JSONObject jb = resources.getJSONObject(j);
			    String product_key = jb.getString("product_key");
			    double resuource_num = jb.getDouble("resuource_num");
			    if (product_key.equalsIgnoreCase(ability_type[i]) && resuource_num > 0) {// 资源存在并且剩余数量大于0
				resources.remove(j);// 已经匹配到的不需要再次匹配
				match = true;
				break;
			    }
			}
			if (match) {// 资源存在并且剩余数量大于0
			    resultData.put(ability_type[i], "1");
			} else {
			    resultData.put(ability_type[i], "0");
			}
		    }
		}
	    }
	} else {
	    resultData.put("result", "9999");
	    resultData.put("desc", result.getString("desc"));
	}
	return resultData;
    }

    public static void main(String[] arg) throws Exception {
	OperationPlatformCustAccountServiceImpl s = new OperationPlatformCustAccountServiceImpl();
	// s.getAskCode("GZQ", "cardpay");
	// s.queryOauthRelationUser("test623", "test06233", "test06233");
	// s.queryResourcesAndAccountInfo("gaoxs20160705", "", "");
	// s.getChargeItems("gaoxs20160705", "YONYOU", "-1", "all", "all", "",
	// "", "1", "10");
	System.out.println(s.getNumberByCallCode("111", "00F57953494DB1429E31332C4BAD5AB5"));// A1B2C3D4
    }

    @Override
    public String getNumberByCallCode(String callCode, String appKey) {
	String number = "";
	JSONObject result;
	try {
	    // 拼写相应传递参数
	    JSONObject jsonParam = new JSONObject();
	    jsonParam.put("app_key", appKey);
	    jsonParam.put("callCode", callCode);
	    // 调用运营平台
	    String Myurl = url + "/CombinationServer/queryAppNumber";
	    // String Myurl =
	    // "http://test.cloud.yonyoutelecom.cn/CombinationServer/queryAppNumber";
	    String data = HttpRequest.postData(Myurl, jsonParam.toString());
	    if (StringUtils.isNotEmpty(data)) {
		result = JSONObject.fromObject(data);
		if ("0000".equals(result.getString("flag"))) {
		    if (result.containsKey("data")) {
			number = result.getJSONObject("data").optString("callNumber").replaceAll("-", "");
		    }
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error("通过业务平台号码编码查询号码失败", e);
	}
	return number;
    }
}
